package com.yksj.healthtalk.ui.friend;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.db.DictionaryHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.WheelUtils;

public class FriendSearchAboutDoctorActivity extends BaseFragmentActivity
		implements OnClickListener {

	private TextView mOfficeTextView;// 科室
	private TextView mJobTitleTextView;// 职称
	private EditText mSpecialtyEditText;// 专长
	private DictionaryHelper dictionaryHelper;
	private final int DIALOG_QUERY = 001;
	private final int WHAT_DOCTOR = 002;
	private final int WHAT_CITY = 1;
	private TextView mCacheTextView;
	private View mainView;
	private View wheelView;
	private PopupWindow pop;
	private EditText hospitalNameEditText;
	private LinkedHashMap<String, String> keshiData = new LinkedHashMap<String, String>();
	private LinkedHashMap<String, String> titles = new LinkedHashMap<String, String>();
	private List<Map<String, String>> proList = new ArrayList<Map<String, String>>();
//	private List<Map<String, String>> infolayList = new ArrayList<Map<String, String>>();
	private Map<String, List<Map<String, String>>> infolayMap = new HashMap<String, List<Map<String, String>>>();
	private CustomerInfoEntity mCustomerInfoEntity;

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case WHAT_DOCTOR:
				removeDialog(DIALOG_QUERY);
				break;

			default:
				break;
			}
		};
	};
	private TextView mLocaleTextView;
	private HashMap<String, List<Map<String, String>>> cityMap;
	private String areaCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setContentView(R.layout.friend_search_aboutdoctor);
		dictionaryHelper = DictionaryHelper.getInstance(this);
		initWidget();
		initData();
		// 科室
		if (titles == null || titles.size() == 0) {
			showDialog(DIALOG_QUERY);
			queryData();
		}
		// 地区
		if (proList == null || proList.size() == 0) {
			queryData1();
		}
	}

	private void setCityData() {
		// if(!proList.isEmpty())
		// return;
		cityMap = new HashMap<String, List<Map<String, String>>>();
		proList = DictionaryHelper.getInstance(this).setCityData(this, cityMap);
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("name", getString(R.string.limit_no));
		hashMap.put("code", "0");
		// 每项加个全部
		for (Map<String, String> map : proList) {
			String name = map.get("name");
			cityMap.get(name).add(0, hashMap);
		}
		proList.add(0, hashMap);

		List<Map<String, String>> arr = new ArrayList<Map<String, String>>();
		arr.add(hashMap);
		cityMap.put(getString(R.string.limit_no), arr);
		// isLoad = true;
		handler.sendEmptyMessage(WHAT_CITY);
	}

	private void queryData1() {
		new Thread(new Runnable() {
			@Override
			public void run() {
//				infolayList = dictionaryHelper.setInfolayData(
//						FriendSearchAboutDoctorActivity.this, infolayMap);
				if (proList.size() == 0) {
					setCityData();
				}
				// else {
				// isLoad = true;
				// }
			}

		}).start();

	}

	private void queryData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				keshiData.put(getString(R.string.limit_no), "0");
				keshiData.putAll(dictionaryHelper.queryKeShi(getBaseContext()));

				titles.clear();
				titles.put(getString(R.string.limit_no), "0");
				LinkedHashMap<String, String> list = DictionaryHelper
						.getInstance(FriendSearchAboutDoctorActivity.this)
						.querydoctorTitles(getBaseContext());
				list.remove("不详");
				titles.putAll(list);
				titles.remove("未知");
				handler.sendEmptyMessage(WHAT_DOCTOR);
			}
		}).start();
	}

	private void initData() {
		titleLeftBtn.setText(R.string.back);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setText(R.string.sure);
		
		titleTextV.setText(R.string.by_condition);
		initWheel();
		mCustomerInfoEntity = getIntent().getParcelableExtra(
				"mCustomerInfoEntity");
		if (mCustomerInfoEntity == null) {
			mCustomerInfoEntity = new CustomerInfoEntity();
		}
		// 默认0是找朋友 1 是找医生
		mCustomerInfoEntity.setType(1);

		if (mCustomerInfoEntity != null) {
			// 科室编码
			if (mCustomerInfoEntity.getOfficeName2() != null
					&& !mCustomerInfoEntity.getOfficeName2().equals("")
					&& !mCustomerInfoEntity.getOfficeName2().equals(
							getString(R.string.limit_no))) {
				mOfficeTextView.setText(mCustomerInfoEntity
						.getOfficeName2());
				mOfficeTextView.setTextColor(getResources().getColorStateList(
						R.color.tag_note));
			} else {
				mOfficeTextView.setTextColor(getResources().getColorStateList(
						R.color.tab_txt_gray));
			}
			// 专长
			if (mCustomerInfoEntity.getSpecial() != null
					&& !mCustomerInfoEntity.getSpecial().equals("")) {
				mSpecialtyEditText.setText(mCustomerInfoEntity.getSpecial());
				mSpecialtyEditText.setTextColor(getResources()
						.getColorStateList(R.color.tag_note));
			} else {
				mSpecialtyEditText.setTextColor(getResources()
						.getColorStateList(R.color.tab_txt_gray));
			}
			// 职称
			if (mCustomerInfoEntity.getDoctorTitle() != null
					&& !mCustomerInfoEntity.getDoctorTitle().equals("")
					&& !mCustomerInfoEntity.getDoctorTitleName().equals(
							getString(R.string.limit_no))) {
				mJobTitleTextView.setText(mCustomerInfoEntity
						.getDoctorTitleName());
				mJobTitleTextView.setTextColor(getResources()
						.getColorStateList(R.color.tag_note));
			} else {
				mJobTitleTextView.setTextColor(getResources()
						.getColorStateList(R.color.tab_txt_gray));
			}
			// 医院
			if (mCustomerInfoEntity.getHospital() != null
					&& !mCustomerInfoEntity.getHospital().equals("")) {
				hospitalNameEditText.setText(mCustomerInfoEntity.getHospital());
				hospitalNameEditText.setTextColor(getResources()
						.getColorStateList(R.color.tag_note));
			} else {
				hospitalNameEditText.setTextColor(getResources()
						.getColorStateList(R.color.tab_txt_gray));
			}

			// 地点
			if (mCustomerInfoEntity.getAreaName() != null
					&& !mCustomerInfoEntity.getAreaName().equals("")) {
				mLocaleTextView.setText(mCustomerInfoEntity.getAreaName());
				mLocaleTextView.setTextColor(getResources().getColorStateList(
						R.color.tag_note));
			}

		}
		mSpecialtyEditText.setTextColor(getResources().getColorStateList(
				R.color.tab_txt_gray));
		hospitalNameEditText.setTextColor(getResources().getColorStateList(
				R.color.tab_txt_gray));
	}

	/**
	 * 初始化滚轮View
	 */
	private void initWheel() {
		LayoutInflater inflater = LayoutInflater.from(this);
		mainView = inflater.inflate(R.layout.friend_search, null);
		wheelView = inflater.inflate(R.layout.wheel, null);
		Button wheelCancel = (Button) wheelView.findViewById(R.id.wheel_cancel);
		Button wheelSure = (Button) wheelView.findViewById(R.id.wheel_sure);

		wheelCancel.setOnClickListener(this);
		wheelSure.setOnClickListener(this);

		pop = new PopupWindow(wheelView, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
	}

	private void initWidget() {
		initTitle();
		mOfficeTextView = (TextView) findViewById(R.id.office_tv);
		mJobTitleTextView = (TextView) findViewById(R.id.job_title_tv);
		mSpecialtyEditText = (EditText) findViewById(R.id.specialty_et);
		hospitalNameEditText = (EditText) findViewById(R.id.hospital_name);
		mLocaleTextView = (TextView) findViewById(R.id.find_locale);

		// 监听器
		mOfficeTextView.setOnClickListener(this);
		mJobTitleTextView.setOnClickListener(this);
		mLocaleTextView.setOnClickListener(this);
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			// setResult(-1);
			finish();
			break;
		case R.id.title_right2:
			beginSearchDoctor();
			Intent intent = new Intent(this, DoctorSearchMainActivity.class);
			intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
			setResult(0, intent);
			finish();
			break;
		case R.id.office_tv:
			setSingleData(mOfficeTextView, keshiData);
			break;
		case R.id.job_title_tv:
			setSingleData(mJobTitleTextView, titles);
			break;
		case R.id.find_locale:
			setCity();
			break;
		case R.id.wheel_sure:
			if (pop != null) {
				pop.dismiss();
			}
			mCacheTextView.setText(WheelUtils.getCurrent());
			if (!WheelUtils.getCurrent().equals(getString(R.string.limit_no))) {
				mCacheTextView.setTextColor(getResources().getColorStateList(
						R.color.tag_note));
			}
			if (mCacheTextView == mLocaleTextView) {
				areaCode = WheelUtils.getCode();
				if ("".equals(areaCode))
					areaCode = WheelUtils.getFirstCode();
				else
					areaCode = WheelUtils.getCode();
			}
			break;
		case R.id.wheel_cancel:
			if (pop != null) {
				pop.dismiss();
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 设置滚轮 城市数据
	 */
	private void setCity() {
		mCacheTextView = mLocaleTextView;
		// code = mCityCode;
		WheelUtils.setDoubleWheel(this, proList, cityMap, mainView, pop,
				wheelView);
	}

	/**
	 * 开始搜索医生
	 */
	private void beginSearchDoctor() {
		FriendUtil.setCustomerInfoEntityOthersDefault(mCustomerInfoEntity, 2);
		// 医生名称
		String mDoctorName;
		mCustomerInfoEntity.setRealname("");

		// 科室编码
		String mOffice;
		if (!(mOffice = mOfficeTextView.getText().toString().trim())
				.equals(getString(R.string.limit_no))) {
			if (keshiData.get(mOffice) == null) {
				mCustomerInfoEntity.setOfficeCode1("0");
				mCustomerInfoEntity
						.setOfficeName1(getString(R.string.limit_no));
			} else {
				mCustomerInfoEntity.setOfficeCode1(
						keshiData.get(mOffice));
				mCustomerInfoEntity.setOfficeName1(mOffice);
			}
		} else {
			mCustomerInfoEntity.setOfficeCode1("0");
			mCustomerInfoEntity
					.setOfficeName1(getString(R.string.limit_no));
		}
		// 专长
		String mSpecialty;
		if (!(((mSpecialty = mSpecialtyEditText.getText().toString().trim()) == null) || mSpecialty
				.equals(""))) {
			mCustomerInfoEntity.setSpecial(mSpecialty);
		} else {
			mCustomerInfoEntity.setSpecial("");
		}

		// 职称
		String title;
		if (!(title = mJobTitleTextView.getText().toString().trim())
				.equals(getString(R.string.limit_no))) {
			if (titles.get(title) == null) {
				mCustomerInfoEntity.setDoctorTitle("0");
				mCustomerInfoEntity
						.setDoctorTitleName(getString(R.string.limit_no));
			} else {
				mCustomerInfoEntity.setDoctorTitle(titles.get(title));
				mCustomerInfoEntity.setDoctorTitleName(title);
			}
		} else {
			mCustomerInfoEntity.setDoctorTitle("0");
			mCustomerInfoEntity
					.setDoctorTitleName(getString(R.string.limit_no));
		}
		// 医院
		if (!hospitalNameEditText.getText().toString().trim().equals("")) {
			mCustomerInfoEntity.setHospital(hospitalNameEditText.getText()
					.toString().trim());
		} else {
			mCustomerInfoEntity.setHospital("");
		}

		// 地点
		if (!mLocaleTextView.getText().toString().trim().equals("")
				&& areaCode != null) {
			mCustomerInfoEntity.setAreaCode(Integer.valueOf(areaCode));
			mCustomerInfoEntity.setAreaName(mLocaleTextView.getText()
					.toString());
		} else {
			mCustomerInfoEntity.setAreaCode(0);
			mCustomerInfoEntity.setAreaName(getString(R.string.limit_no));
		}
	}

	/**
	 * 设置职称、科室滚轮
	 * 
	 * @param text
	 * @param map
	 */
	private void setSingleData(TextView text, HashMap<String, String> map) {
		mCacheTextView = text;
		// code = mCityCode;
		ArrayList<String> arr = new ArrayList<String>(map.keySet());
		String[] str = new String[arr.size()];
		arr.toArray(str);
		WheelUtils.setSingleWheel(this, str, mainView, pop, wheelView, false);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(-1);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
}
